package pers.yaoliguo.bms.control;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.yaoliguo.bms.control.view.Message;
import pers.yaoliguo.bms.control.view.UserView;
import pers.yaoliguo.bms.uitl.MD5Util;

/**
 * @ClassName:       loginControl
 * @Description:    TODO
 * @author:            yao
 * @date:            2017年6月24日        下午8:47:02
 */
@Controller
@RequestMapping(value="/LoginControl")
public class LoginControl extends BaseControl{
	
	@ResponseBody
	@RequestMapping(value="/login/auth")
	public Object loginAuth(UserView userView){
		
		Message<UserView> msg = new Message<UserView>();
		
		if(userView.getAccount() != null && userView.getPassword() != null && !"".equals(userView.getAccount()) && !"".equals(userView.getPassword())){
			
			String account = userView.getAccount();
			String password = userView.getPassword();
			String code = userView.getCode();
			String sourceCode = (String) getDataFromSession("code");
			
			if(code.equals(sourceCode)){
				
				UsernamePasswordToken token = new UsernamePasswordToken(account, MD5Util.encrypt(password),false);
				Subject currentUser = SecurityUtils.getSubject();
				try {
					currentUser.login(token);
				} catch(IncorrectCredentialsException e){
					msg.setResult("400");
					msg.setInfo("密码错误");
					
					return msg;
					
				} catch (AuthenticationException e) {
					msg.setResult("500");
					msg.setInfo(e.getMessage());
					
					return msg;
				}
				try{
					currentUser.isPermitted(account);
				} catch(AuthenticationException e) {
					msg.setResult("500");
					msg.setInfo(e.getMessage());
					return msg;
				}
				
				msg.setResult("200");
				msg.setInfo("登录成功！");
				
			}else{
				msg.setResult("400");
				msg.setInfo("验证码错误！");
			}
			
			
			
		}else{
			msg.setResult("400");
			msg.setInfo("请输入帐号密码！");
		}
		
		return msg;
	}
	
	@ResponseBody
	@RequestMapping(value="/logOut")
	public Object logOut(HttpServletRequest request){
		
		Message<UserView> msg = new Message<UserView>();
		try {
			Subject currentUser = SecurityUtils.getSubject();
			currentUser.logout();
			msg.setResult("200");
			msg.setInfo("正常退出！");
		} catch (Exception e) {
			msg.setResult("500");
			msg.setInfo("有异常了！"+e.getMessage());
		}
		
		
		return msg;
	}
	

}
